package freeboard.controller;

import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import freeboard.dto.FreeBoardDTO;
import freeboard.dto.ListDTO;
import freeboard.model.service.FreeBoardService;

@Controller
public class FreeBoardController {
	private FreeBoardService service;
	public FreeBoardController(FreeBoardService service){
		this.service = service;
	}
	//글쓰기
	@RequestMapping("/writeContent.do")
	public ModelAndView writeContent(HttpSession session, FreeBoardDTO fdto){
		ModelAndView mv=null;
		try {
			service.writeContent(fdto,session);
			session.setAttribute("fdto", fdto);
			mv=new ModelAndView("/res/show_content");
		} catch (Exception e) {
			e.printStackTrace();
			mv = new ModelAndView("res/error", "error_message", e.getMessage());
		}
		return mv;
	}
	// 전체 글 목록 보여주기
	@RequestMapping("/freeboardList.do")
		public ModelAndView boardList(HttpServletRequest request, HttpServletResponse response){
			ModelAndView mv = null;
			String page = request.getParameter("page");
			System.out.println(page);
			try {
				ListDTO ldto = new ListDTO();
				if(page.equals(null)||page.equals("")){
					page ="1";
				}
				ldto=service.selectBoardListByPage(Integer.parseInt(page));
				request.setAttribute("ldto", ldto);
				mv=new ModelAndView("/res/list");
				
			} catch (NumberFormatException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				
				mv = new ModelAndView("res/error", "error_message", e.getMessage());
				
			}
			return mv;
		}
	// 상세 내용 보여기주기 및 이전글 다음 글 
	@RequestMapping("/getContentByNo.do")
		public ModelAndView getContentByNo(HttpServletRequest request, HttpServletResponse response, HttpSession session){
			ModelAndView mv = new ModelAndView();
			int no =Integer.parseInt(request.getParameter("no")); 
			String page = request.getParameter("page");
			FreeBoardDTO fdto = null;
			try {
				fdto=service.getContentByNO(no);
				System.out.println(fdto);
				session.setAttribute("fdto", fdto);
				session.setAttribute("page", page);
				session.setAttribute("next", service.getNext(no));
				session.setAttribute("prev", service.getPrev(no));
				mv.setViewName("/res/show_content");
			} catch (SQLException e) {
				e.printStackTrace();
				
				mv = new ModelAndView("res/error", "error_message", e.getMessage());
			}
			return mv;
		}
}